﻿Imports Global_Visas_Business_Layer
Imports System.Text
Imports System.Data
Imports System.ComponentModel
Imports System.IO
Imports Microsoft.VisualBasic
Partial Public Class frmEditCase

    Public Shared EMAILBODYSTRING As String
    Public Shared EMAILSUBJECTSTRING As String
    Public Shared EMAILBCCSTRING As String
    Public Shared EMAILFROMSTRING As String
    Public Shared EMAILTOSTRING As String
    Private _OldCase As Cases.CaseInfo
    Private _ThisCase As Cases.CaseInfo

    Private _IsLoading As Boolean

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub

    Private Sub EditCase_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loaded

        Dim myProduct As Products.ProductInfo

        _IsLoading = True
        Try
            GeneralTasks.ChangeTheme(Me)
            GeneralTasks.EnumerateandFill(Me.LogicalChildren)
            ' disable certain controls
            ' xxx when you add the admin security you can enable these if they have permission
            Me.drpCandidate.IsEnabled = False

            Select Case Security._SecurityLevel
                Case SecurityLevel.NormalUser
                    drpBranch.IsEnabled = False
                    drpCoordinator.IsEnabled = False
                    drpCoordinator.IsEnabled = False
                    drpProductType.IsEnabled = False
                    drpProduct.IsEnabled = False
                    drpCW.IsEnabled = False
                Case SecurityLevel.BranchManager
                    drpBranch.IsEnabled = True
                    drpProduct.IsEnabled = True
                    drpProductType.IsEnabled = True
                    drpCW.IsEnabled = True
                Case SecurityLevel.AdminUser
                    drpBranch.IsEnabled = True
                    drpProduct.IsEnabled = True
                    drpProductType.IsEnabled = True
                    drpCW.IsEnabled = True
                    'drpBranch.Enabled = False
            End Select

            'Populate form with case data
            Me._ThisCase = Cases.GetCaseInfo(GlobalCRM.CurrentCaseID)
            Me._OldCase = Me._ThisCase

            Dim SQL As New StringBuilder

            ' if case has not been sold
            ' get list of candidates
            If GlobalCRM.CurrentCompanyID > 0 Then
                With SQL
                    .Append("Select Person_ID, Person_Fname + ' ' + Person_LName as PersonName")
                    .Append(" From D_Person INNER JOIN L_Roles ON D_Person.Person_CompanyRoleID = L_Roles.Role_ID")
                    .Append(" WHERE Person_CompanyID = " & Me._ThisCase.CompanyId)
                    .Append(" AND Role_Employee =0 ")
                    .Append(" order by personname")
                End With
            Else
                With SQL
                    .Append("Select Person_ID, Person_Fname + ' ' + Person_LName as PersonName from d_person")
                    .Append(" where person_id = " & Me._ThisCase.CandidateId)
                End With
            End If
            ' populate candidate drop down list
            With Me.drpCandidate
                .SelectedValuePath = "Person_ID"
                .DisplayMemberPath = "PersonName"
                .ItemsSource = CType(CommonDataFunctions.GetSQLDatatable(SQL.ToString), IListSource).GetList
                .SelectedValue = Me._ThisCase.CandidateId
            End With


            If Me._ThisCase.CaseStatusId < 100 Then
                Me.drpCandidate.IsEnabled = True
            Else
                Me.drpCandidate.IsEnabled = False
            End If

            If Me._ThisCase.CaseStatusId >= 100 Then
                'disable things too late to change
                Me.drpProduct.IsEnabled = False
                Me.drpProductType.IsEnabled = False
                'Me.txtExtRef.Enabled = True
            End If

            ' check if a company
            If GlobalCRM.CurrentCompanyID > 0 Then
                Me.drpContact.IsEnabled = True
            Else
                Me.drpContact.IsEnabled = False
            End If



            With Me.drpSalesCon

                .DisplayMemberPath = "con_name"
                .SelectedValuePath = "con_id"
                .ItemsSource = CType(CommonDataFunctions.ConsultantList(, , Me._ThisCase.SalesConid), IListSource).GetList
            End With

            With Me.drpCW

                .DisplayMemberPath = "con_name"
                .SelectedValuePath = "con_id"
                .ItemsSource = CType(CommonDataFunctions.ConsultantList(, , Me._ThisCase.CaseWorkerId), IListSource).GetList
            End With

            With Me.drpCoordinator

                .DisplayMemberPath = "con_name"
                .SelectedValuePath = "con_id"
                .ItemsSource = CType(CommonDataFunctions.ConsultantList(, , Me._ThisCase.CaseCoordinatorID), IListSource).GetList
            End With

            With Me.drpContact

                .SelectedValuePath = "person_id"
                .DisplayMemberPath = "personname"
                .ItemsSource = CType(CommonDataFunctions.CorporateContactList(GlobalCRM.CurrentCompanyID), IListSource).GetList
            End With

            myProduct = Products.GetProductInfo(Me._ThisCase.Productid)
            
            With Me.drpProductType
                .SelectedValuePath = "ProductType_ID"
                .DisplayMemberPath = "Product Type"
                .ItemsSource = CType(Products.ProductTypesList(), IListSource).GetList
                .SelectedValue = Me._ThisCase.ProductTypeId
            End With

            With Me.drpProduct
                .DisplayMemberPath = "product_name"
                .SelectedValuePath = "product_id"
                .ItemsSource = CType(Products.ProductListByType(Me._ThisCase.ProductTypeId, Me._ThisCase.Productid), IListSource).GetList
                .SelectedValue = Me._ThisCase.Productid
            End With

            With Me.drpBranch
                .DisplayMemberPath = "Branch_Name"
                .SelectedValuePath = "Branch_ID"
                .ItemsSource = CType(CommonDataFunctions.BranchList(), IListSource).GetList
                .SelectedValue = myProduct.BranchID
            End With

            'Me.drpBranch.SelectedValue = myProduct.BranchID

            'CommonFunc.FindResigned(Me.drpSalesCon)
            'CommonFunc.FindResigned(Me.drpCW)
            'CommonFunc.FindResigned(Me.drpCoordinator)

            Select Case Security._SecurityLevel
                Case SecurityLevel.NormalUser
                    'Me.drpBranch.Enabled = False
                    If _ThisCase.SalesConid <> GlobalCRM.CurrentConID Then
                        Me.drpSalesCon.IsEnabled = False
                    Else
                        Me.drpSalesCon.IsEnabled = True
                    End If
                    Me.drpCW.IsEnabled = False
                    Me.drpCoordinator.IsEnabled = False
                Case SecurityLevel.BranchManager
                    'Me.drpBranch.Enabled = False
                Case SecurityLevel.AdminUser
                    Me.drpBranch.IsEnabled = True
                    Me.drpSalesCon.IsEnabled = True
                    Me.drpCW.IsEnabled = True
                    Me.drpCoordinator.IsEnabled = True
            End Select

            ' populate the controls
            If Not IsNothing(Me._ThisCase) Then
                With Me._ThisCase
                    Me.drpProductType.SelectedValue = .ProductTypeId
                    Me.drpProduct.SelectedValue = .Productid
                    Me.drpSalesCon.SelectedValue = .SalesConid
                    Me.drpCW.SelectedValue = .CaseWorkerId
                    Me.drpContact.SelectedValue = .Contactid
                    Me.drpCoordinator.SelectedValue = .CaseCoordinatorID
                    Me.txtExtRef.Text = .ExtRef
                    Me.txtCriticalType.Text = .CriticalType
                    If .ExpiryDate.Year > 1900 Then
                        Me.txtExpiryDate.Text = .ExpiryDate
                    End If
                    If .CriticalDate.Year > 1900 Then
                        Me.txtCriticalDate.Text = .CriticalDate
                    End If
                    If .PoliceMedsDate.Year > 1900 Then
                        Me.txtPoliceDate.Text = .PoliceMedsDate
                    End If
                    If .EntryDate.Year > 1900 Then
                        Me.txtEntryDate.Text = .EntryDate
                    End If

                End With
            End If


            If Security._SecurityLevel = SecurityLevel.NormalUser Then
                If Me._ThisCase.CaseCoordinatorID <> GlobalCRM.CurrentConID Then
                    Me.drpCoordinator.IsEnabled = False
                End If
                If Me._ThisCase.CaseWorkerId <> GlobalCRM.CurrentConID Then
                    Me.drpCW.IsEnabled = False
                End If
                If Me._ThisCase.CaseCoordinatorID <> GlobalCRM.CurrentConID Then
                    Me.drpCoordinator.IsEnabled = False
                End If
            End If


            If Me._ThisCase.CaseStatusId < 100 Then
                drpCandidate.IsEnabled = True
                drpProduct.IsEnabled = True
                drpBranch.IsEnabled = True
                drpProductType.IsEnabled = True
            Else
                If Security._SecurityLevel = SecurityLevel.BranchManager Or Security._SecurityLevel = SecurityLevel.AdminUser Then
                    drpCandidate.IsEnabled = True
                    drpProduct.IsEnabled = True
                    drpBranch.IsEnabled = True
                    drpProductType.IsEnabled = True
                ElseIf Security._SecurityLevel = SecurityLevel.NormalUser Then
                    drpCandidate.IsEnabled = False
                    drpProduct.IsEnabled = False
                    drpBranch.IsEnabled = False
                    drpProductType.IsEnabled = False
                End If

            End If


        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "frmEditCase.Load", False)
        Finally
            _IsLoading = False
            myProduct = Nothing
        End Try




    End Sub

    '    Private Sub drpProductType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)'

    '       With Me.drpProduct
    '            .DisplayMember = "product_name"
    '          .ValueMember = "product_id"
    '         .DataSource = CommonSQL.ProductListByType(Me.drpProductType.SelectedValue)
    '    End With


    '    End Sub

    Private Sub btnExp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExp.Click

        Me.txtExpiryDate.Text = CommonFuncs.GetPopUpCalendarDate(Me.txtExpiryDate.Text)

        'frmCalendarPopUp.ShowDialog()
        'Me.txtExpiryDate.Text = Format(GlobalCRM.DatePopUpDate, "dd-MMM-yyyy")
    End Sub

    Private Sub btnCrit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCrit.Click

        Me.txtCriticalDate.Text = CommonFuncs.GetPopUpCalendarDate(Me.txtCriticalDate.Text)

        'frmCalendarPopUp.ShowDialog()
        'Me.txtCriticalDate.Text = Format(GlobalCRM.DatePopUpDate, "dd-MMM-yyyy")
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Dim Changes As New StringBuilder
        Dim ResetCharges As Boolean
        Dim Task As Boolean
        Dim bChangeParty As Boolean = False
        Dim blnCWEmail As Boolean
        Dim LinkedCase As Cases.CaseInfo
        Dim tsk As New TasksEvents
        Try
            CommonFuncs.BeginTrans()
            Dim caseStageFrom As Integer = Cases.GetCaseStage(GlobalCRM.CurrentCaseID).StageNumber
            If Me.drpProductType.SelectedIndex = -1 Then
                CommonFuncs.DisplayMessage("Cannot have a blank product type", CommonDialog.CustomDialogIcons.Information, "Product Type")
                Exit Sub
            End If
            'Commented on 5/3/2008 by  Sumathivinayak S as per the comments by tester. 
            'If Me.drpCW.SelectedIndex = -1 Then
            '    MsgBox("Cannot have a blank caseworker", MsgBoxStyle.Exclamation, "Case Worker")
            '    Exit Sub
            'End If

            If Me.drpSalesCon.SelectedIndex = -1 Then
                CommonFuncs.DisplayMessage("Cannot have a blank sales consultant", CommonDialog.CustomDialogIcons.Information, "Sales Consultant")
                Exit Sub
            End If

            'If Me.txtCriticalDate.Text <> "" And Not IsDate(Me.txtCriticalDate.Text) Then
            '    CommonFuncs.DisplayMessage("Not a valid critical date", CommonDialog.CustomDialogIcons.Information, "Critical Date")
            '    Exit Sub
            'End If

            'If Me.txtExpiryDate.Text <> "" And Not IsDate(Me.txtExpiryDate.Text) Then
            '    CommonFuncs.DisplayMessage("Not a valid expiry date", CommonDialog.CustomDialogIcons.Information, "Expiry Date")
            '    Exit Sub
            'End If

            'If Me.txtEntryDate.Text <> "" And Not IsDate(Me.txtEntryDate.Text) Then
            '    CommonFuncs.DisplayMessage("Not a valid entry date", CommonDialog.CustomDialogIcons.Information, "Entry Date")
            '    Exit Sub
            'End If

            'If Me.txtPoliceDate.Text <> "" And Not IsDate(Me.txtPoliceDate.Text) Then
            '    CommonFuncs.DisplayMessage("Not a valid Police/Meds date", CommonDialog.CustomDialogIcons.Information, "Date")
            '    Exit Sub
            'End If

            'If Me.txtExtRef.Text.Trim.Length > 100 Then
            '    CommonFuncs.DisplayMessage("External Ref too long (max 100 chars)", CommonDialog.CustomDialogIcons.Information, "Error")
            '    Me.txtExtRef.Focus()
            '    Exit Sub
            'End If

            'If Me.txtCriticalType.Text.Trim.Length > 50 Then
            '    CommonFuncs.DisplayMessage("Critical Type too long (Max 50 chars)", CommonDialog.CustomDialogIcons.Information, "Error")
            '    Me.txtExtRef.Focus()
            '    Exit Sub
            'End If

            With Me._ThisCase
                .Productid = Me.drpProduct.SelectedValue

                .CaseWorkerId = Me.drpCW.SelectedValue
                .SalesConid = Me.drpSalesCon.SelectedValue
                .CandidateId = Me.drpCandidate.SelectedValue
                .Contactid = Me.drpContact.SelectedValue
                .CaseCoordinatorID = Me.drpCoordinator.SelectedValue
                .ExtRef = Me.txtExtRef.Text.Trim
                .CriticalType = Me.txtCriticalType.Text.Trim
                If IsDate(Me.txtCriticalDate.Text) Then
                    .CriticalDate = CDate(Me.txtCriticalDate.Text)
                Else
                    .CriticalDate = Nothing
                End If
                If IsDate(Me.txtExpiryDate.Text) Then
                    .ExpiryDate = CDate(Me.txtExpiryDate.Text)
                Else
                    .ExpiryDate = Nothing
                End If
                If IsDate(Me.txtEntryDate.Text) Then
                    .EntryDate = CDate(Me.txtEntryDate.Text)
                Else
                    .EntryDate = Nothing
                End If
                If IsDate(Me.txtPoliceDate.Text) Then
                    .PoliceMedsDate = CDate(Me.txtPoliceDate.Text)
                Else
                    .PoliceMedsDate = Nothing
                End If
            End With


            With Changes

                If Me.drpProduct.SelectedValue <> Me._OldCase.Productid Then
                    .Append("Product changed from " & Me._OldCase.Productid & " to " & Me.drpProduct.Text & vbCrLf)

                    'Prompt to see if they want the defaults updating.
                    If MsgBox("Do you want to reset the default charges and document requirements for this case to reflect the new product type?", vbYesNo + vbQuestion, "Update defaults") = MsgBoxResult.Yes Then
                        ResetCharges = True
                        .Append("Charges and document requirements reset for new product type." & vbCrLf)
                    Else
                        .Append("Charges and document requirements NOT reset." & vbCrLf)
                    End If
                End If

                If Me.drpCW.SelectedValue <> Me._OldCase.CaseWorkerId Then
                    Task = True
                    blnCWEmail = True
                    bChangeParty = True
                    .Append("Caseworker changed from " & Me._OldCase.CaseWorkerName & " to " & Me.drpCW.Text & vbCrLf)

                    'TasksEvents.GblFunc_Add_Event("Case Review", "This case must be reviewed before proceeding.", TasksEvents.EventStatus.Task, GlobalCRM.CurrentCaseID, CommonSQL.EventTypes.EventCase, 0, 0, drpCW.SelectedValue, DateAdd(DateInterval.Day, 4, Now))
                End If

                If Me.drpSalesCon.SelectedValue <> Me._OldCase.SalesConid Then
                    bChangeParty = True
                    .Append("Sales Consultant changed from " & CommonDataFunctions.GetConsultantName(Me._OldCase.SalesConid) & " to " & Me.drpSalesCon.Text & vbCrLf)
                End If

                If Me.drpCoordinator.SelectedValue <> Me._OldCase.CaseCoordinatorID Then
                    bChangeParty = True
                    .Append("Case Co-ordinator changed from " & Me._OldCase.CaseCoordinatorName & " to " & Me.drpCoordinator.Text & vbCrLf)
                    tsk.GblFunc_Add_Event("Case Review", "This case must be reviewed before proceeding.", TasksEvents.EventStatus.Task, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, 0, 0, drpCoordinator.SelectedValue, DateAdd(DateInterval.Day, 4, Now))
                End If

                If Me.drpCandidate.SelectedValue <> Me._OldCase.CandidateId Then
                    .Append("Candidate changed from " & Me._OldCase.CandidateName & " to " & Me.drpCandidate.Text & vbCrLf)
                End If

                If Me.drpContact.SelectedValue <> Me._OldCase.Contactid Then
                    .Append("Contact changed from " & Me._OldCase.Contactid & " to " & Me.drpContact.Text & vbCrLf)
                End If

                '    If Me.txtExtRef.Text <> Me._OldCase.ExtRef Then
                '        .Append("ExtRef changed from " & Me._OldCase.ExtRef & " to " & Me.txtExtRef.Text & vbCrLf)
                '    End If

                '    If Me.txtCriticalType.Text <> Me._OldCase.CriticalType Then
                '        .Append("Critical Type changed from " & Me._OldCase.CriticalType & " to " & Me.txtCriticalType.Text & vbCrLf)
                '    End If

                '    If Me.txtCriticalDate.Text <> Me._OldCase.CriticalDate.ToString Then
                '        If Me._OldCase.CriticalDate.Year > 1900 Then
                '            .Append("Critical Date changed from " & Me._OldCase.CriticalDate & " to " & Me.txtCriticalDate.Text & vbCrLf)
                '        End If
                '    End If

                '    If Me.txtExpiryDate.Text <> Me._OldCase.ExpiryDate.ToString Then
                '        If Me._OldCase.ExpiryDate.Year > 1900 Then
                '            .Append("Expiry Date changed from " & Me._OldCase.ExpiryDate & " to " & Me.txtExpiryDate.Text & vbCrLf)
                '        End If
                '    End If

                '    If Me.txtEntryDate.Text <> Me._OldCase.EntryDate.ToString Then
                '        If Me._OldCase.EntryDate.Year <> 1900 Then
                '            .Append("Entry Date changed from " & Me._OldCase.EntryDate & " to " & Me.txtEntryDate.Text & vbCrLf)
                '        End If
                '    End If

                '    If Me.txtPoliceDate.Text <> Me._OldCase.PoliceMedsDate.ToString Then
                '        If Me._OldCase.PoliceMedsDate.Year <> 1900 Then
                '            .Append("Police/Meds Date changed from " & Me._OldCase.PoliceMedsDate & " to " & Me.txtPoliceDate.Text & vbCrLf)
                '        End If
                '    End If

            End With

            If Not Cases.UpdateCase(Me._ThisCase) Then
                If Not Cases.UpdateCase(Me._ThisCase) Then
                    Exit Sub
                End If
            End If

            If bChangeParty = True Then
                LinkedCase = Cases.GetCaseInfo(Me._ThisCase.LinkedCaseID)
                If Me._ThisCase.LinkedCaseID <> 0 Then
                    With LinkedCase
                        .CaseWorkerId = Me._ThisCase.CaseWorkerId
                        .CaseCoordinatorID = Me._ThisCase.CaseCoordinatorID
                        .SalesConid = Me._ThisCase.SalesConid
                    End With
                    Cases.UpdateCase(LinkedCase)
                End If
            End If



            If ResetCharges Then
                Accounts.DeleteCharges(GlobalCRM.CurrentCaseID, "Changed Product For Case", True)
                Accounts.LoadDefaultCharges(GlobalCRM.CurrentCaseID)

                Cases.ResetCaseDocs(GlobalCRM.CurrentCaseID, Me._ThisCase.Productid, GlobalCRM.CurrentConName, Me._ThisCase.CandidateId, Me._ThisCase.CompanyId)
            End If

            tsk.GblFunc_Add_Event("Case details changed", Changes.ToString, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase)

            If Me.drpCW.SelectedValue <> Me._OldCase.CaseWorkerId Then
                'update the case assigned date 11:46AM 28/04/2009 Sumathivinayak S
                If Cases.UpdateDateAssigned(GlobalCRM.CurrentCaseID, GlobalCRM.CurrentConID) = True Then
                    tsk.GblFunc_Add_Event("Case Assigned", "The case has been assigned on " & Format(DateTime.Today), TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase)
                Else
                    CommonFuncs.DisplayMessage("The case assigned date is not updated in the system. Please contact IT to update the information", CommonDialog.CustomDialogIcons.Information, "Assign Error")
                End If

            End If
            If Task Then

                Dim Msg As New StringBuilder

                Msg.Append("You have been set as the caseworker for this case, please review all details")

                tsk.GblFunc_Add_Event("Review Case", Msg.ToString, TasksEvents.EventStatus.Task, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, 0, 0, Me._ThisCase.CaseWorkerId, Now.AddDays(2))
            End If


            'Process Case Audits

            If Me._ThisCase.CaseWorkerId <> Me._OldCase.CaseWorkerId Then
                CommonDataFunctions.Gblfunc_Add_CaseAudit(GlobalCRM.CurrentCaseID, 3, Me._OldCase.CaseWorkerId, Me._ThisCase.CaseWorkerId, GlobalCRM.CurrentConID)
            End If

            If Me._ThisCase.SalesConid <> Me._OldCase.SalesConid Then
                CommonDataFunctions.Gblfunc_Add_CaseAudit(GlobalCRM.CurrentCaseID, 2, Me._OldCase.SalesConid, Me._ThisCase.SalesConid, GlobalCRM.CurrentConID)
            End If

            If Me._ThisCase.Productid <> Me._OldCase.Productid Then
                CommonDataFunctions.Gblfunc_Add_CaseAudit(GlobalCRM.CurrentCaseID, 1, Me._OldCase.Productid, Me._ThisCase.Productid, GlobalCRM.CurrentConID)
            End If

            If Me._ThisCase.CandidateId <> Me._OldCase.CandidateId Then
                CommonDataFunctions.Gblfunc_Add_CaseAudit(GlobalCRM.CurrentCaseID, 4, Me._OldCase.CandidateId, Me._ThisCase.CandidateId, GlobalCRM.CurrentConID)
            End If

            If Me._ThisCase.Contactid <> Me._OldCase.Contactid Then
                CommonDataFunctions.Gblfunc_Add_CaseAudit(GlobalCRM.CurrentCaseID, 5, Me._OldCase.Contactid, Me._ThisCase.Contactid, GlobalCRM.CurrentConID)
            End If

            '
            'MJG 02/06/06  Wrapped this in condition statement as was firing regardless of what details had changed
            If Me._OldCase.CaseWorkerId <> Me._ThisCase.CaseWorkerId Then

                'MJG 07/06/06 Migration staff don't want this feature
                If Cases.GetCaseDepartment(GlobalCRM.CurrentCaseID) <> 3 Then
                    'Call Form_Fm_MainDisplay.Btn_Case_BlankEmail_Click()
                    'Form_Fm_SendMail.Combo_SystemMail = 124

                    'Call Form_Fm_SendMail.Combo_SystemMail_AfterUpdate()
                End If
            End If
            Dim caseStageTo As Integer = Cases.GetCaseStage(GlobalCRM.CurrentCaseID).StageNumber
            If (caseStageFrom <> caseStageTo) Then
                Admin.BookTheRelevantTask(caseStageFrom, caseStageTo)
            End If
            Me.Close()
            CommonFuncs.CommitTrans()
            'Sendemail
            If blnCWEmail Then
                SendEmailForEditCase(Me._ThisCase, GlobalCRM.CurrentCandidateID, CommonDataFunctions.getCustomizationdata("EmailTemplate_ToAllocate"))
            End If
        Catch ex As Exception
            CommonFuncs.RollbackTrans()
            CommonFuncs.ErrorHandler(ex, "frmEditCase.btnSave_Click")
            tsk = Nothing
        Finally
        End Try
    End Sub



    Private Sub btnPolice_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPolice.Click

        Me.txtPoliceDate.Text = CommonFuncs.GetPopUpCalendarDate(Me.txtPoliceDate.Text)

        'frmCalendarPopUp.ShowDialog()
        'Me.txtPoliceDate.Text = Format(GlobalCRM.DatePopUpDate, "dd-MMM-yyyy")
    End Sub

    Private Sub btnEntry_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEntry.Click

        Me.txtEntryDate.Text = CommonFuncs.GetPopUpCalendarDate(Me.txtEntryDate.Text)

        'frmCalendarPopUp.ShowDialog()
        'Me.txtEntryDate.Text = Format(GlobalCRM.DatePopUpDate, "dd-MMM-yyyy")
    End Sub

    Private Sub drpProductType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles drpProductType.SelectionChanged

        If _IsLoading = True Then
            Exit Sub
        End If
        'With Me.drpCaseProduct
        '    .DisplayMemberPath = "Product_Name"
        '    .SelectedValuePath = "Product_ID"
        '    .ItemsSource = CType(Products.ProductList(Me.drpCaseType.SelectedValue), IListSource).GetList
        '    .SelectedIndex = -1
        'End With

        With Me.drpProduct
            .SelectedValuePath = "Product_ID"
            .DisplayMemberPath = "Product_Name"
            .ItemsSource = CType(Products.ProductList(Me.drpProductType.SelectedValue), IListSource).GetList
            .SelectedIndex = -1
        End With

    End Sub
    Public Shared Sub SendEmailForEditCase(ByVal mycaseInfo As Cases.CaseInfo, ByVal myPerson As Integer, ByVal templateid As Integer)
        Dim sqlbldr As New StringBuilder
        Dim EmailFrom, EmailTo As String
        Dim dt As DataTable

        Dim tsk As New TasksEvents
        Dim cmn As New CommonFuncs
        Dim frmEmailCaseNavigation As frmEmailCaseNavigation
        Try


            'Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader
            'Dim TemplateID As Integer = CType(configurationAppSettings.GetValue("EmailTemplate_ToAllocate", GetType(System.String)), String)
            'Dim DataType As Integer
            'Dim DataID As Long
            If templateid > 0 Then
                Dim myTemplate As CommonDataFunctions.EmailTemplateInfo
                myTemplate = CommonDataFunctions.GetEmailTemplate(templateid)
                'Dim StrSQL As String

                'If EmailFrom = string.empty Then
                '    MsgBox("The email ID of the case worker is not configured in the system. Please contact IT", MsgBoxStyle.Critical, "Error")
                '    Exit Sub
                'End If
                'sqlbldr = New StringBuilder
                'sqlbldr.Append("Select EmailAddress_Address from D_EmailAddress where EmailAddress_personID = " & myPerson)
                'EmailTo = DB.GetSQLScalar(sqlbldr.ToString)
                'If EmailTo Is Nothing Then
                '    MsgBox("The Email address of the client is not found in the system. Hence email has not been sent", MsgBoxStyle.OkOnly, "Email Not sent")
                '    Exit Sub
                'End If
                Dim DataType As Integer
                Dim DataID As Long
                If GlobalCRM.CurrentCompanyID = 0 Then
                    DataType = 1
                    DataID = mycaseInfo.CaseId
                    sqlbldr = New StringBuilder
                    sqlbldr.Append("Select EmailAddress_Address from D_EmailAddress where EmailAddress_personID = " & myPerson)
                    EmailTo = CommonDataFunctions.GetSQLScalar(sqlbldr.ToString)
                    If EmailTo Is Nothing Then
                        MsgBox("The Email address of the client is not found in the system. Hence email has not been sent", MsgBoxStyle.OkOnly, "Email Not sent")
                        Exit Sub
                    End If
                Else
                    DataType = 3
                    DataID = GlobalCRM.CurrentCompanyID
                    'Fetch the company's contact and send email to associated ocntact and not the candidate
                    sqlbldr = New StringBuilder
                    sqlbldr.Append("select EmailAddress_Address from D_EmailAddress where EmailAddress_personID in (select case_contactid from d_case where case_candidateid = " & myPerson & ")")
                    EmailTo = CommonDataFunctions.GetSQLScalar(sqlbldr.ToString)
                    If EmailTo Is Nothing Then
                        MsgBox("The Email address of the client is not found in the system. Hence email has not been sent", MsgBoxStyle.OkOnly, "Email Not sent")
                        Exit Sub
                    End If
                End If
                Dim StrSQLBookmarks As String = String.Empty
                Dim intCount As Integer = 1
                Dim txtfile As String = System.IO.Path.GetTempPath & "CRMTemp\sample.txt"
                Directory.CreateDirectory(System.IO.Path.GetTempPath & "CRMTemp")

                Dim oWrite As System.IO.StreamWriter
                oWrite = File.CreateText(System.IO.Path.GetTempPath & "CRMTemp\sample.txt")
                oWrite.Write(myTemplate.Body)
                oWrite.Close()

                Dim oRead As System.IO.StreamReader
                Dim LineIn As String
                Dim strNew() As String
                Dim strnew1() As String
                Dim i As Integer
                Dim c As New Collection
                Dim cData As Collection = Nothing
                Dim cIndex As New Collection
                Dim bln As Boolean
                oRead = IO.File.OpenText(txtfile)
                While oRead.Peek <> -1
                    LineIn = oRead.ReadLine()
                    strNew = Split(LineIn, "[")
                    For i = 0 To strNew.Length - 1
                        strnew1 = Split(strNew(i).ToString, "]")
                        If strnew1.Length > 1 Then
                            'StrSQLBookmarks = strnew1(0).ToString
                            StrSQLBookmarks = StrSQLBookmarks & "'" & strnew1(0).ToString & "',"
                            If cIndex.Contains(strnew1(0).ToString) = False Then
                                cIndex.Add(i, strnew1(0).ToString)
                                bln = True
                            End If
                            If bln Then
                                c.Add(strnew1(0).ToString)
                            End If
                            bln = False
                        End If
                    Next
                End While
                oRead.Close()

                StrSQLBookmarks = Microsoft.VisualBasic.Left(StrSQLBookmarks, (Len(StrSQLBookmarks) - 1))
                StrSQLBookmarks = "(" & StrSQLBookmarks & ")"

                Dim sql1 As New StringBuilder
                With sql1
                    .Append("SELECT BookMark_Text as BMName")
                    .Append(" FROM I_SL_Bookmarks")
                    .Append(" WHERE Bookmark_Text in " & StrSQLBookmarks & "")
                    '.Append(" AND Bookmark_VersionID <= " & 1)
                    .Append(" GROUP BY BookMark_Text")
                End With
                dt = CommonDataFunctions.GetSQLDatatable(sql1.ToString)
                If Not dt Is Nothing Then
                    If dt.Rows.Count > 0 Then
                        Dim StrBMData As String = String.Empty
                        cData = New Collection
                        For i = 0 To dt.Rows.Count - 1
                            If dt.Rows(i).Item("BMName") <> "" Then
                                If GlobalCRM.CurrentCompanyID <> 0 Then
                                    If dt.Rows(i).Item("BMName") = "CandidateDearName" Then
                                        StrBMData = Letters.Gblfunc_Get_BookmarkData("ContactDearName", DataID, DataType)
                                        cData.Add(StrBMData, dt.Rows(i).Item("BMName"))
                                    Else
                                        DataType = 1
                                        DataID = mycaseInfo.CaseId
                                        StrBMData = Letters.Gblfunc_Get_BookmarkData(dt.Rows(i).Item("BMName"), DataID, DataType)
                                        cData.Add(StrBMData, dt.Rows(i).Item("BMName"))
                                    End If
                                Else
                                    StrBMData = Letters.Gblfunc_Get_BookmarkData(dt.Rows(i).Item("BMName"), DataID, DataType)
                                    cData.Add(StrBMData, dt.Rows(i).Item("BMName"))
                                End If
                            End If
                            If StrBMData = "EmailError_IT_Contact" Then
                                System.IO.File.Delete(txtfile)
                                Directory.Delete(System.IO.Path.GetTempPath & "CRMTemp\")
                                Exit Sub
                            End If
                        Next
                    End If
                End If
                oRead = IO.File.OpenText(txtfile)
                Dim strRep As String = oRead.ReadToEnd
                oRead.Close()
                Dim OpToEmail As String
                For i = 1 To cData.Count
                    If OpToEmail = String.Empty Then
                        OpToEmail = strRep.Replace("[" & c.Item(i) & "]", cData.Item(c.Item(i)))
                    Else
                        OpToEmail = OpToEmail.Replace("[" & c.Item(i) & "]", cData.Item(c.Item(i)))
                    End If
                Next
                'Dim subj As String = "Global Visas Case Update"

                'Dim Signature As String
                Dim intSignatureBranchID As Integer = CommonDataFunctions.GetBranchID(mycaseInfo.CaseWorkerId)
                Dim Signature As String
                'Dim intSignatureOfficeID = CType(configurationAppSettings.GetValue("ConIDHeadOffice", GetType(System.Int16)), Integer)
                'Dim Signature As String = CType(configurationAppSettings.GetValue("ConIDHeadOffice", GetType(System.String)), String)
                Dim intSignatureConID As String = CommonDataFunctions.getCustomizationdata("ConID" & intSignatureBranchID)

                'Select Case intSignatureBranchID
                '    Case 1
                '        intSignatureConID = CType(configurationAppSettings.GetValue("ConIDHeadOffice", GetType(System.String)), String)
                '    Case 2
                '        intSignatureConID = CType(configurationAppSettings.GetValue("ConIDIndiaOffice", GetType(System.String)), String)
                '    Case 6
                '        'crm bug fix - for SA signatureerror 
                '        intSignatureConID = CType(configurationAppSettings.GetValue("ConIDSAOffice", GetType(System.String)), String)
                '    Case 4
                '        intSignatureConID = CType(configurationAppSettings.GetValue("ConIDCAOffice", GetType(System.String)), String)
                '    Case 3
                '        intSignatureConID = CType(configurationAppSettings.GetValue("ConIDUSAOffice", GetType(System.String)), String)
                'End Select
                sqlbldr = New StringBuilder
                sqlbldr.Append("Select Con_EMail from L_Consultant where Con_ID = " & intSignatureConID)
                EmailFrom = CommonDataFunctions.GetSQLScalar(sqlbldr.ToString)
                If intSignatureConID <> "" Then
                    Signature = CommonDataFunctions.GblFunc_Get_Sigfile(intSignatureConID)
                End If
                OpToEmail = OpToEmail & vbCrLf & Signature
                'EMAILBCCSTRING
                CommonDataFunctions.EMAILBODYSTRING = OpToEmail
                CommonDataFunctions.EMAILSUBJECTSTRING = GlobalCRM.subj
                CommonDataFunctions.EMAILFROMSTRING = EmailFrom
                CommonDataFunctions.EMAILTOSTRING = EmailTo
                frmEmailCaseNavigation = New frmEmailCaseNavigation
                frmEmailCaseNavigation.btnBack.Content = "Cancel"
                frmEmailCaseNavigation.ShowDialog()

                Dim Success As Integer = Letters.GblFunc_Send_MailEngine(EMAILTOSTRING, EMAILFROMSTRING, EMAILSUBJECTSTRING, EMAILBODYSTRING, , EMAILBCCSTRING)
                EMAILSUBJECTSTRING = String.Empty
                EMAILBODYSTRING = String.Empty
                EMAILBCCSTRING = String.Empty
                Dim Msg As New StringBuilder
                With Msg
                    .Append("Email Sent" & vbCrLf & vbCrLf & "To: " & EmailTo)

                    .Append(vbCrLf & vbCrLf & "Sent via mail engine")
                    .Append(vbCrLf & "Subject: " & GlobalCRM.subj)

                    .Append(vbCrLf & "Message: " & vbCrLf & vbCrLf & OpToEmail)
                End With

                tsk.GblFunc_Add_Event("Send Email", Msg.ToString, TasksEvents.EventStatus.SingleEvent, GlobalCRM.CurrentCaseID, TasksEvents.EventTypes.EventCase, , , , , 1)
                If Success = 1 Then
                    'MsgBox("Email has been sent to the client successfully.", MsgBoxStyle.Information, "Success")
                End If
                System.IO.File.Delete(txtfile)
                cmn.ForceDeleteTempDir()
            End If
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "commonFunc.SendEmailForEditCase", True)

            tsk = Nothing
            cmn = Nothing
            Exit Sub
        Finally
            frmEmailCaseNavigation = Nothing
        End Try
    End Sub
    Private Sub drpBranch_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles drpBranch.SelectionChanged

        If _IsLoading = True Then
            Exit Sub
        End If

        With Me.drpProductType
            .DisplayMemberPath = "producttype_name"
            .SelectedValuePath = "producttype_id"
            .ItemsSource = CType(Products.ProductTypeList(drpBranch.SelectedValue, Me._ThisCase.ProductTypeId, False), IListSource).GetList
        End With
        drpProductType_SelectedIndexChanged(sender, e)
        drpProduct.ItemsSource = Nothing

        With Me.drpProduct
            .SelectedValuePath = "product_id"
            .DisplayMemberPath = "product_name"
            .ItemsSource = CType(Products.ProductListByType(Me.drpProductType.SelectedValue, -1), IListSource).GetList
            .SelectedIndex = -1
        End With

    End Sub


    Private Sub txtCriticalDate_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles txtCriticalDate.SelectedDateChanged
        Me.txtCriticalDate.Text = (New CommonFuncs).FormatDate(txtCriticalDate.SelectedDate)
    End Sub

    Private Sub txtCriticalType_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles txtCriticalType.SelectedDateChanged
        Me.txtCriticalType.Text = (New CommonFuncs).FormatDate(txtCriticalType.SelectedDate)

    End Sub

    Private Sub txtEntryDate_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles txtEntryDate.SelectedDateChanged
        Me.txtEntryDate.Text = (New CommonFuncs).FormatDate(txtEntryDate.SelectedDate)

    End Sub

    Private Sub txtExpiryDate_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles txtExpiryDate.SelectedDateChanged
        Me.txtExpiryDate.Text = (New CommonFuncs).FormatDate(txtExpiryDate.SelectedDate)

    End Sub



    Private Sub txtPoliceDate_SelectedDateChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles txtPoliceDate.SelectedDateChanged
        Me.txtPoliceDate.Text = (New CommonFuncs).FormatDate(txtPoliceDate.SelectedDate)

    End Sub
End Class
